/**
 * created by jsq on 2017/10/9
 * 银行定义重新开发了，之前的接口废弃
 * 字段也改变
 * 没有联动二级城市了
 */
import React from 'react';
import {connect} from 'react-redux';
import {Button, Badge, Popover, Popconfirm, Tabs,Modal,Upload,Icon,message} from 'antd';
import SearchArea from 'components/search-area';
import {messages} from "share/common";
import ResizeTable from 'components/resize-table'
import 'styles/basic-data/bank-definition/bank-definition.scss';
import SlideFrame from 'components/slide-frame';
import CreateOrUpdateBank from 'containers/basic-data/bank-definition/create-or-update-bank';
import ImportErrInfo from 'components/template/import-err-info';
import BSService from 'containers/basic-data/bank-definition/bank-definition.service';
import FileSaver from 'file-saver';
const TabPane = Tabs.TabPane;

class BankDefinition extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      slideFrameKey: 0,
      loading: true,
      showImportBankModel:false,//导入自定义银行弹窗
      progressImportErrInfo: 1,
      showImportErrInfo: false,
      transactionOID: null,
      errorsList: [
      ],
      fileList: [],
      flieUploading: false,//文件是否正在上传

      data: [],
      country: [],//需要传入侧边栏的数据
      label: "customBank",
      slideFrame: {
        title: "",
        visible: false,
        params: {}
      },
      tabs: [
        {key: 'customBank', name: messages('basic-data.key1'/*自定义银行*/)},
        {key: 'commonBank', name: messages('basic-data.key2'/*通用银行*/)},
      ],
      //点击顶部搜索时要参数
      searchParams: {
        bankCode: "",
        bankBranchName: "",
        countryCode: "",
        openAccount: ""
      },
      //顶部搜索区域
      searchForm: [
        {
          type: 'input',
          id: 'bankCode',
          label: messages('basic-data.key3'/*银行代码*/)
        },
        {
          type: 'input',
          id: 'bankBranchName',
          label: messages('basic-data.key4'/*支行名称*/)
        },
        {
          type: 'selector',
          id: 'countryCode',
          label: messages('basic-data.key5'/*国家*/),
          selectorType: 'newCountry',
          showSearch: true
        },
        {
          type: 'input',
          id: 'openAccount',
          options: [],
          event: 'ADDRESS_CHANGE',
          label: messages('basic-data.key6'/*开户地*/),
        }
      ],
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      // 自定义银行表格
      customBankColumns: [
        {
          title: messages('basic-data.key5'/*国家*/),
          key: "countryName",
          dataIndex: 'countryName',
          width: '10%',
          render: desc => <span>{desc ? <Popover overlayStyle={{maxWidth: 500}}
                                                 placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        },
        {
          width: '15%',
          title: messages('basic-data.key3'/*银行代码*/),
          key: "bankCode",
          dataIndex: 'bankCode',
          render: desc => <span>{desc ? <Popover overlayStyle={{maxWidth: 500}}
                                                 placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        },
        {
          width: '10%',
          title: 'Swift Code',
          key: "Swift Code",
          dataIndex: 'swiftCode',
          render: desc => <span>{desc ? <Popover overlayStyle={{maxWidth: 500}}
                                                 placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        },
        {
          title: messages('basic-data.key7'/*银行名称*/),
          key: "bankName",
          dataIndex: 'bankName',
          render: desc => <span>{desc ? <Popover overlayStyle={{maxWidth: 500}}
                                                 placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        },
        {
          title: messages('basic-data.key4'/*支行名称*/),
          key: "bankBranchName",
          dataIndex: 'bankBranchName',
          render: desc => <span>{desc ? <Popover overlayStyle={{maxWidth: 500}}
                                                 placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        },
        {
          title: messages('basic-data.key6'/*开户地*/),
          key: "openAccount",
          dataIndex: 'openAccount',
          render: desc => <span>{desc ? <Popover overlayStyle={{maxWidth: 500}}
                                                 placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        },
        {
          title: messages('basic-data.key8'/*详细地址*/),
          key: "detailAddress",
          dataIndex: 'detailAddress',
          render: desc => <span>{desc ? <Popover overlayStyle={{maxWidth: 500}}
                                                 placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        },
        {
          /*状态*/
          title: messages('common.column.status'),
          key: 'status',
          width: '10%',
          dataIndex: 'enable',
          render: enable => (
            <Badge status={enable ? 'success' : 'error'}
                   text={enable ? messages('common.status.enable') :
                     messages('common.status.disable')}/>
          )
        },
        {
          title: messages('common.operation'),
          key: "operation",
          dataIndex: 'operation',
          render: (text, record) => (
            <span>
              <a href="#" onClick={(e) => this.editItem(e, record)}>{messages('common.edit')}</a>
              <span className="ant-divider"/>
              <Popconfirm onConfirm={(e) => this.deleteItem(e, record)}
                          title={messages('basic-data.key24',{controlRule: record.controlRuleName}/*你确认要删除？*/)}>
                <a href="#" onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                }}>
                  {messages('common.delete')}
                  </a>
              </Popconfirm>
            </span>)
        }
      ],
      // 通用银行表格
      commonBankColumns: [
        {
          title: messages('basic-data.key5'/*国家*/),
          key: "countryName",
          dataIndex: 'countryName',
          width: '10%',
          render: desc => <span>{desc ? <Popover  overlayStyle={{maxWidth: 500}}
                                                  placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        },
        {
          width: '15%',
          title: messages('basic-data.key3'/*银行代码*/),
          key: "bankCode",
          dataIndex: 'bankCode',
          render: desc => <span>{desc ? <Popover overlayStyle={{maxWidth: 500}}
                                                 placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        },
        {
          width: '10%',
          title: 'Swift Code',
          key: "Swift Code",
          dataIndex: 'swiftCode',
          render: desc => <span>{desc ? <Popover overlayStyle={{maxWidth: 500}}
                                                 placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        },
        {
          title: messages('basic-data.key7'/*银行名称*/),
          key: "bankName",
          dataIndex: 'bankName',
          render: desc => <span>{desc ? <Popover overlayStyle={{maxWidth: 500}}
                                                 placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        },
        {
          title: messages('basic-data.key4'/*支行名称*/),
          key: "bankBranchName",
          dataIndex: 'bankBranchName',
          render: desc => <span>{desc ? <Popover overlayStyle={{maxWidth: 500}}
                                                 placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        },
        {
          title: messages('basic-data.key6'/*开户地*/),
          key: "openAccount",
          dataIndex: 'openAccount',
          render: desc => <span>{desc ? <Popover overlayStyle={{maxWidth: 500}}
                                                 placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        },
        {
          title: messages('basic-data.key8'/*详细地址*/),
          key: "detailAddress",
          dataIndex: 'detailAddress',
          render: desc => <span>{desc ? <Popover overlayStyle={{maxWidth: 500}}
                                                 placement="topLeft" content={desc}>{desc}</Popover> : '-'}</span>
        }
      ],
      columns: [],
      tabKey: 0,
    }
  }

  deleteItem = (e, record) => {
    this.setState({loading: true});
    BSService.deleteSelfBank(record.id).then(response => {
      this.getList();
    }).catch((e) => {
      this.setState({loading: false});
    })
  };

  //暂时不需要联动下级城市
  clearHandle = (event, value) => {
    this.setState({
      searchParams: {
        bankCode: "",
        bankBranchName: "",
        countryCode: "",
        openAccount: ""
      }
    }, () => {
      this.getList()
    })
  };
  componentDidMount() {
    let {customBankColumns} = this.state;
    this.setState({
      columns: customBankColumns
    });
    this.getList();
    this.getCountrys();
  }

  //Tabs点击
  onChangeTabs = (key) => {
    let {columns, commonBankColumns, pagination, customBankColumns, tabKey} = this.state;
    if (key === 'customBank') {
      columns = customBankColumns
    } else {
      columns = commonBankColumns
    }
    pagination.page = 0;
    pagination.pageSize = 10;
    pagination.current = 1;
    this.setState({
      loading: true,
      pagination,
      data: [],
      label: key,
      columns: columns,
      tabKey: tabKey + 1,
      searchParams: {
        bankCode: "",
        bankBranchName: "",
        countryCode: "",
        openAccount: ""
      },
    }, () => {
      this.getList()
    });
  };

  editItem = (e, record) => {
    e.preventDefault();
    e.stopPropagation();
    let slideFrame = {};
    let slideFrameKey = this.state.slideFrameKey;
    slideFrameKey++;
    slideFrame.title = messages('basic-data.key9'/*编辑银行*/);
    slideFrame.visible = true;
    slideFrame.params = record;
    slideFrame.params.countryData = this.state.country;
    this.setState({
      slideFrame,
      slideFrameKey
    })
  };

  handleCreate = () => {
    let slideFrame = {
      params: {}
    };
    let slideFrameKey = this.state.slideFrameKey;
    slideFrameKey++;
    slideFrame.title = messages('basic-data.key10'/*新建银行*/);
    slideFrame.visible = true;
    slideFrame.params.countryData = this.state.country;
    this.setState({
      slideFrame,
      slideFrameKey
    });
  };

  //获取公司下的银行数据
  getList() {
    this.setState({loading: true});
    let params = this.state.searchParams;
    let ps = {
      page: this.state.pagination.page,
      size: this.state.pagination.pageSize
    }

    if (this.state.label === 'customBank') {
      BSService.getSelfBankList(params, ps)
        .then((response) => {
          let pagination = this.state.pagination;
          pagination.total = Number(response.headers['x-total-count']);
          this.setState({
            loading: false,
            data: response.data,
            pagination
          });
        })
    } else {
      BSService.getSystemBankList(params, ps)
        .then((response) => {
          let pagination = this.state.pagination;
          pagination.total = Number(response.headers['x-total-count']);
          this.setState({
            loading: false,
            data: response.data,
            pagination
          });
        })
    }
  }

  getCountrys = () => {
    BSService.getCountries(this.props.language.locale)
      .then((response) => {
        let country = response.data.map((item) => {
          item.label = item.country;
          item.value = item.code;
          if (item.value === "CHN000000000") {
            item.children = [];
          }
          return item;
        });
        this.setState({
          country
        })
        this.getChinaState();
      });
  }

// ---------分割线------获取省市------
  // 8号上线了，6号的时候：
  // 产品要求说："用户选择中国的时候，把省与市联动"
  // 我需要一个接口，一次性获取中国的所有省市，后端说8号给不了，
  // 我这边就占时循环调接口，把省市掉出来，以此添加用户体验
  //获取中国的所有省
  getChinaState = () => {
    let params = {
      language: this.props.language.code === 'zh_cn' ? "zh_cn" : "en_us",
      code: 'CHN000000000',
      vendorType: "standard",
      page: 0,
      size: 1000
    }
    BSService.getStates(params)
      .then((response) => {
        let children = response.data.map((item) => {
          item.label = item.state;
          item.value = item.code;
          item.children = [];
          this.getCityByCode(item.code);
          return item;
        })
        this.setChinaState(children);
      })
  }
  //设置国家的省
  setChinaState = (children) => {
    let countrys = this.state.country;
    for (let i = 0; i < countrys.length; i++) {
      if (countrys[i].code === "CHN000000000") {
        countrys[i].children = children;
      }
    }
  }
  //获取市
  getCityByCode = (code) => {
    let params = {
      language: this.props.language.code === 'zh_cn' ? "zh_cn" : "en_us",
      code: code,
      vendorType: "standard"
    }
    BSService.getCities(params)
      .then((response) => {
        let children = response.data.map((item) => {
          item.label = item.city;
          item.value = item.code;
          return item;
        })
        this.setChinaCity(children, code);
      })
  }

  setChinaCity = (children, code) => {
    let countrys = this.state.country;
    let china = '';
    //选出中国
    for (let i = 0; i < countrys.length; i++) {
      if (countrys[i].code === "CHN000000000") {
        china = countrys[i].children;
        break;
      }
    }
    //挨个省设置城市
    for (let i = 0; i < china.length; i++) {
      if (china[i].code === code) {
        china[i].children = children;
        break;
      }
    }
  }
// ---------分割线------获取省市------
  handleSearch = (params) => {
    let pagination = this.state.pagination;
    pagination.page = 0;
    pagination.current = 1;
    this.setState({
      searchParams: params,
      pagination
    }, () => {
      this.getList();
    })
  };

  handleCloseSlide = (params) => {
    let slideFrame = this.state.slideFrame;
    slideFrame.visible = false;
    this.setState({
      slideFrame
    });
    if (params) {
      this.setState({loading: true});
      this.getList()
    }
  };

  //分页点击
  onChangePager = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        current: pagination.current,
        page: pagination.current - 1,
        pageSize: pagination.pageSize,
        total: pagination.total
      }
    }, () => {
      this.getList();
    })
  };
  handleImportShow = () => {
    this.setState({
      showImportBankModel:true
    })
  }
  handleExport = () => {
    this.setState({
      loading: true,
    })
    BSService.exportSelfBank()
      .then((res) => {
        this.setState({
          loading: false,
        })
        let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        let name = messages('basic-data.key1'/*自定义银行*/);
        FileSaver.saveAs(b, `${name}.xlsx`);
      })
      .catch((res) => {
        this.setState({
          loading: false,
        })
      })
  }
  cancelImport = () => {
    this.setState({
      showImportBankModel:false
    })
  }
  //下载模板
  downloadTemplate=()=>{
    BSService.downloadSelfBankTemp()
      .then((res)=>{
        let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        let name = messages('basic-data.key11'/*自定义银行模板*/);
        FileSaver.saveAs(b, `${name}.xlsx`);
      })
      .catch((res)=>{

      })
  }
  handleFileUpload = () => {
    const {fileList} = this.state;
    const formData = new FormData();
    // fileList.forEach((file) => {
    //   formData.append('files[]', file);
    // });
    formData.append('file', fileList[0]);
    this.setState({
      uploading: true,
      flieUploading: true,
    });

    BSService.importSelfBank(formData)
      .then((res) => {
        this.setState({
          uploading: false,
          fileList: [],
          flieUploading: false,
          showImportBankModel:false,
          transactionOID: res.data.transactionOID//这个transactionOID在导出错误信息的时候，需要用到
        }, () => {
          this.showImportErrInfo();
          this.showTransactionLogDialog(this.state.transactionOID);   // 将参数传给dialog
        });
      })
      .catch((res) => {
        this.setState({
          uploading: false,
          flieUploading: false,
        })
      })
  }

  showTransactionLogDialog = (transactionOID) => {
    BSService.importSelfBankErr(transactionOID)
      .then((res) => {
        let data = res.data;
        if (data.totalEntities === 0) {
          this.hideImportErrInfo();
          return;
        } else {
          let errors = data.errors;
          let errorsList = this.getErrorDataByerrors(errors);
          let progressImportErrInfo = this.getProgressByData(data);
          this.setState({
            progressImportErrInfo,
            errorsList
          })
          if ((data.successEntities + data.failureEntities) != data.totalEntities) {
            let gapTime = 500;
            setTimeout(() => {
              //请求频率涉及到一个算法
              this.showTransactionLogDialog(this.state.transactionOID);   // 将参数传给dialog
            },gapTime)
          }else {
            //导入完成了
            this.getList();
            if(this.state.errorsList.length === 0 && progressImportErrInfo === 100){
              message.success(messages("common.operate.success"));
              this.hideImportErrInfo();
            }
          }
        }
      })
  }
  //获取百分进度
  getProgressByData = (data) => {
    return Math.round((data.failureEntities + data.successEntities) * 100 / data.totalEntities);
  }
  //通过错误信息，解析成表格
  getErrorDataByerrors = (errs) => {
    let data = [];
    for(let key in errs){
      let row = {};
      row.line = errs[key];
      if(row.line.length > 1){
        let _line = [];
        for(let i = 0; i < row.line.length; i++){
          _line.push(row.line[i]);
          if(i < row.line.length-1){
            _line.push(",");
          }
        }
        row.line = _line;
      }
      row.msg = key;
      data.push(row);
    }
    return data;
  }
  //银行导入错误信息
  exportFailedLog=()=>{
    BSService.exportSelfBankErr(this.state.transactionOID)
      .then((res)=>{
        let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        let name = messages('basic-data.key12'/*银行导入错误信息*/);
        FileSaver.saveAs(b, `${name}.xlsx`);
      })
      .catch((res)=>{

      })
  }
  renderBtns = (tabName) => {

    if (tabName === "commonBank") {
      return null;
    } else {
      return (
        <div>
          <Button type="primary" onClick={this.handleCreate}>{messages('common.create')}</Button>
          <Button onClick={this.handleImportShow}>
            {messages('basic-data.key13'/*批量导入*/)}
          </Button>
          <Button onClick={this.handleExport}>
            {messages('basic-data.key14'/*批量导出*/)}
          </Button>
        </div>
      )
    }
  }
  //人员导入的错误信息-start
  showImportErrInfo = () => {
    this.setState({
      showImportErrInfo: true
    })
  }

  hideImportErrInfo = () => {
    this.setState({
      showImportErrInfo: false
    })
  }

  //人员导入的错误信息-end
  renderTabs() {
    return (
      this.state.tabs.map(tab => {
        return <TabPane tab={tab.name} key={tab.key}/>
      })
    )
  }

  render() {
    const props = {
      onRemove: (file) => {
        this.setState(({fileList}) => {
          const index = fileList.indexOf(file);
          const newFileList = fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: (file) => {
        this.setState(({fileList}) => ({
          fileList: [ file],
        }));
        return false;
      },
      fileList: this.state.fileList,
    };
    const {loading, data, searchForm, pagination, columns, label, slideFrame, tabKey} = this.state;
    return (
      <div className="budget-bank-definition">
        <Tabs onChange={this.onChangeTabs}>
          {this.renderTabs()}
        </Tabs>
        <SearchArea key={tabKey}
                    searchForm={searchForm}
                    clearHandle={this.clearHandle}
                    submitHandle={this.handleSearch}/>
        <div className="table-header">
          <div
            className="table-header-title">{messages('common.total', {total: `${pagination.total}`})}</div>
          {/*共搜索到*条数据*/}
          <div className="table-header-buttons">
            {this.renderBtns(label)}
          </div>
        </div>
        <ResizeTable
          dataSource={data}
          loading={loading}
          pagination={pagination}
          onChange={this.onChangePager}
          columns={columns}
          size="middle"
          bordered/>
        <SlideFrame
          slideFrameKey={this.state.slideFrameKey}
          title={slideFrame.title}
          show={slideFrame.visible}
          content={CreateOrUpdateBank}
          afterClose={this.handleCloseSlide}
          onClose={() => this.setState({slideFrame: {visible: false}})}
          params={slideFrame.params}/>

        <Modal
          closable
          width={800}
          className="pm-import-person-modal"
          title={messages('basic-data.key15'/*导入*/)}
          visible={this.state.showImportBankModel}
          footer={null}
          onCancel={this.cancelImport}
          destroyOnClose={true}
        >
          <div className="import-person-modal-wrap">

            <div className="f-left import-person-modal-left">
              <div>
                <p>
                  {messages('basic-data.key16'/*1.创建导入文件*/)}
                </p>
                <p>
                  {messages('basic-data.key17'/*2.严格按照导入模板整理数据，检查必输事项是否缺少数据*/)}
                </p>
                <p>
                  {messages('basic-data.key18'/*3.关闭文件后，方可进行数据导入*/)}
                </p>
              </div>
              <div className="download-list-item"
                   onClick={this.downloadTemplate}
              >
                {messages('basic-data.key19'/*点击下载模板*/)}
              </div>
            </div>
            <div className="f-right import-person-modal-right">
              <div className="import-person-right-tips">
                {messages('basic-data.key20'/*上传模板*/)}
              </div>
              <div className="upload-file-wrap">
                <Upload {...props}>
                  <Button>
                    <Icon type="upload"/>
                    {messages('basic-data.key21'/*选择一个文件*/)}
                  </Button>
                </Upload>
                <Button
                  className="upload-file-start"
                  type="primary"
                  onClick={this.handleFileUpload}
                  disabled={this.state.fileList.length === 0}
                  loading={this.state.flieUploading}
                >
                  {this.state.flieUploading ? messages('basic-data.key22'/*上传中*/) : messages('basic-data.key23'/*开始上传*/)}
                </Button>

              </div>
            </div>
            <div className="clear"/>
          </div>
        </Modal>
        <ImportErrInfo
          progress={this.state.progressImportErrInfo}
          cancel={this.hideImportErrInfo}
          exportErrInfo={this.exportFailedLog}
          errorsList={this.state.errorsList}
          visible={this.state.showImportErrInfo}/>
      </div>
    )
  }
}

BankDefinition.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
    company: state.login.company,
    language: state.main.language,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(BankDefinition);
